import { ISA, type AirData } from '@/atmosphere'
import { getBADAModel } from './core'
import type { OperationPerformance } from './types'
const G0 = 9.80665

export interface DragItem {
  cL: number // 升力系数
  cD: number // 阻力系数
  TAS: number
  drag: number
}

export interface DragProfile {
  alt: number
  mass: number
  S: number
  rho: number
  line: DragItem[]
}

export function calcDragProfileById(id: string, alt: number): DragProfile {
  const model = getBADAModel(id)!
  return calcDragProfile(model.performance, alt)
}

export function calcNormalDrag(op: OperationPerformance, ad: AirData, tas: number): number {
  const ccL = (2 * op.massRef * 1000.0 * G0) / ad.density / op.S
  const t2 = tas * tas
  const cL = ccL / t2
  const cD = op.cDrag0CR + op.cDrag2CR * cL * cL
  const drag = (cD * ad.density * t2 * op.S) / 2.0
  return drag
}

function calcDragProfile(op: OperationPerformance, alt: number): DragProfile {
  const ad = ISA.getAirData(alt)
  const ccL = (2 * op.massRef * 1000.0 * G0) / ad.density / op.S
  let tas = 40.0
  const ret: DragItem[] = []
  while (tas < 600.0) {
    const t2 = tas * tas
    const cL = ccL / t2
    const cD = op.cDrag0CR + op.cDrag2CR * cL * cL
    const drag = (cD * ad.density * t2 * op.S) / 2.0
    ret.push({ drag, cL, cD, TAS: tas })
    tas += 20.0
  }
  return {
    alt,
    S: op.S,
    rho: ad.density,
    mass: op.massRef,
    line: ret
  }
}
